package com.module.ble.hDu

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.os.RemoteException
import android.util.Log
import com.common.app.data.bean.KeyEvents
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.getContext
import com.common.base.utils.AppUtils
import com.common.base.utils.AppUtils.getPackageName
import com.common.base.utils.JsonUtils
import com.common.base.utils.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserCalorie
import com.module.ble.db.table.UserHeartRate
import com.module.ble.db.table.UserSleepInfo
import com.module.ble.hDu.HDSysUtils.getPhoneUniqueId
import com.module.ble.utils.CommonCusHealthType
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.BleOtherUtil
import com.module.ble.utils.ConnectState
import com.module.ble.utils.SleepModeType
import com.sxr.sdk.ble.keepfit.aidl.IServiceCallback

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/4/22
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class HDServiceImpl :  IServiceCallback.Stub() {
    private val TAG = "HDServiceImpl"
    private var mClassicBtDeviceBtName = ""

    override fun onAuthSdkResult(p0: Int) {
        LogUtils.e(TAG, "HDu-sdk onAuthSdkResult status=$p0")
    }

    override fun onScanCallback(
        p0: String?,
        p1: String?,
        p2: Int,
        p3: String?,
        p4: String?,
        p5: String?,
        p6: String?,
        p7: String?,
        p8: String?
    ) {
    }

    override fun onConnectStateChanged(state: Int) {
        AizoSDKUtil.isConnect = state
        LogUtils.e(TAG, "HDu-sdk onConnectStateChanged： ${state}")
        when (state) {
            ConnectState.STATE_DISCONNECTED -> {
                AizoSDKUtil.mConnectBleDeviceExpandListenerList.forEach {
                    doOnUiThread { it.onDisconnect(AizoSDKUtil.curMac) }
                }
                LogUtils.e(TAG, "HDu-onConnectStateChanged-STATE_DISCONNECTED")
            }
            ConnectState.STATE_CONNECTING -> {
                LogUtils.e(TAG, "HDu-onConnectStateChanged-STATE_CONNECTING")
            }
            ConnectState.STATE_CONNECTED -> {
                HDuSendCommandManage.callSetDeviceTime(AizoSDKUtil.mHDuService)
                HDuSendCommandManage.callSetAppId(
                    AizoSDKUtil.mHDuService,
                    getPhoneUniqueId(AizoSDKUtil.sharedPreferences)
                )
                HDuSendCommandManage.callRemoteSetAutoHeartMode(AizoSDKUtil.mHDuService, true)

                AizoSDKUtil.mServiceConnectionFirst = false
                AizoSDKUtil.mConnectBleDeviceExpandListenerList.forEach {
                    AizoSDKUtil.curMac = AizoSDKUtil.macTemp
                    doOnUiThread { it.onConnect(AizoSDKUtil.curMac) }
                }
                AizoSDKUtil.getDevicePowerState()
                LogUtils.e(TAG, "HDu-onConnectStateChanged-STATE_CONNECTED")
            }
        }
    }

    override fun onAuthDeviceResult(p0: Int) {
    }

    override fun onGetDeviceTime(p0: Int, p1: String?) {
    }

    override fun onSetDeviceTime(p0: Int) {
    }

    override fun onSetUserInfo(p0: Int) {
    }

    /**
     *
     *参数分别为当前时间戳,以秒为单位 ,当前步数,当前距离(米),当前卡路里(大卡)，当前睡眠时间（秒），当前运动总时间，当前记步时间
     *有效的返回值根据类型而定
     *type = 0  当前运动信息
     *返回有效值为：手环当前时间戳,以秒为单位 ,当前步数,当前距离(米),当前卡路里(大卡)，当前睡眠时间（秒）
     *Type = 1 当前跑步信息
     *返回有效值为：当前时间戳,以秒为单位 当前步数 当前运动总时间 当前记步时间
     *
     */
    override fun onGetCurSportData(
        type: Int,
        timestamp: Long,
        step: Int,
        distance: Int,
        cal: Int,
        cursleeptime: Int,
        totalrunningtime: Int,
        steptime: Int
    ) {
        LogUtils.e(TAG, "HDu-sdk onGetCurSportData->${timestamp}---${type}---${step}---${distance}---${cal}---${cursleeptime}---${steptime}---")

        AizoSDKUtil.saveStepsRelatedData(timestamp * 1000, timestamp * 1000, step.toLong(), distance.toDouble())
        val calorieTemp = UserCalorie()
        calorieTemp.createdTime = timestamp * 1000
        calorieTemp.createdTime = timestamp * 1000
        calorieTemp.calorie = cal.toDouble()
        AizoSDKUtil.calorieMultiAdd2DB(calorieTemp)

        if (type == 0) { // 0是运动
//            LiveEventBus.get(KeyEvents.KEY_OV_HUD_SDK_SPORT_DATA).post(HduCurSportData(timestamp,step,distance,cal,cursleeptime,totalrunningtime,steptime))
            AizoSDKUtil.mSportMonitorDataExpandListenerList.forEach {
                doOnUiThread { it.sportInfo(type,timestamp*1000,step,distance,cal,cursleeptime,totalrunningtime,steptime) }
            }
        } else if (type == 1) { // 1是跑步
        }

    }

    override fun onSendVibrationSignal(p0: Int) {
    }

    override fun onSetPhontMode(p0: Int) {
    }

    override fun onSetIdleTime(p0: Int) {
    }

    override fun onSetSleepTime(p0: Int) {
    }

    override fun onGetDeviceBatery(p0: Int, p1: Int) {
        AizoSDKUtil.setElectricityInfo(p0, p1)
    }

    override fun onGetDeviceInfo(
        version: Int,
        macaddress: String?,
        vendorCode: String?,
        productCode: String?,
        result: Int
    ) {
        val ringFirm = AizoSDKUtil.getRingFirm()
        AizoSDKUtil.curRingInfoBean?.let {
            it.ringFirm = ringFirm
            it.ringName = ringFirm
            it.version = version.toString()
            it.vendorCode = vendorCode
            it.productCode = productCode
            it.crcResult = result.toString()
            it.upTime = TimeUtils.getTimeDateLong()
        }
        AizoSDKUtil.updateRingInfo()

        AizoSDKUtil.mBleDeviceInfoExpandListenerList.forEach {
            doOnUiThread { it.onGetDeviceInfo() }
        }
    }

    override fun onSetAlarm(p0: Int) {
    }

    override fun onSetDeviceMode(p0: Int) {
    }

    override fun onSetNotify(p0: Int) {
    }

    /**
     * 实时心率测量回调
     */

    override fun onGetSenserData(
        result: Int,
        timestamp: Long,
        heartrate: Int,
        sleepstatus: Int
    ) {

        if (heartrate <= 0) return
        HDuSendCommandManage.callRemoteSetHeartRateMode(AizoSDKUtil.mHDuService, false)
        val userHeartRate = UserHeartRate()
        userHeartRate.createdTime = timestamp * 1000
        userHeartRate.heartRate = heartrate
        AizoSDKUtil.heartRateRepoAdd2DB(userHeartRate)
        LogUtils.e(TAG, "HDu-sdk onMeasureResult-onGetSenserData->${result}---${userHeartRate.createdTime}---${userHeartRate.heartRate}---${sleepstatus}---")
        AizoSDKUtil.mCusSynthesisHealthExpandListenerList.forEach {
            doOnUiThread {
                it.onMeasureResult(
                    true,
                    CommonCusHealthType.HEARTRATE.value,
                    userHeartRate.createdTime,
                    userHeartRate.heartRate,
                    0,
                    0f,
                    0f
                )
            }
        }
    }

    override fun setAutoHeartMode(p0: Int) {
    }

    override fun onSetDeviceInfo(p0: Int) {
    }

    override fun onSetHourFormat(p0: Int) {
    }



    /**
     * 取得某天详细运动信息回调接口
     * 返回数据 type : 1 运动信息  2 睡眠信息 3 心率信息 12 体温数据
     * 当type = 1 时  step为步数 心率为0（无效）
     * 当type = 2 时  step为睡眠质量数据
     * 如果为0表明没有记录或没有睡眠，有记录时的取值范围为（1-100）。100为最好的睡眠质量，1为最差的睡眠质量） 心率为0（无效）
     * 当type = 3 时  step为0（无效） heartrate为心率值
     * 当type = 12 时 step为体表温度（>300, 无效） heartrate为体温温度（>300, 无效）
     * timestamp: 时间戳（秒）
     * step: 步数
     * heartrate: 心率
     */
    override fun onGetDataByDay(type: Int, timestamp: Long, step: Int, heartrate: Int) {
        if (timestamp <= 0) return
        when (type) {
            1 -> {
                if (step <= 0) return
                AizoSDKUtil.saveStepsRelatedData(timestamp * 1000, timestamp * 1000, step.toLong(), 0.00)
                LogUtils.e(TAG, "HDU:onGetDataByDay step ${BleOtherUtil.allSleepInfo.size}")
//                LogUtils.e(TAG, "HDU:onGetDataByDay step ${JsonUtils.toJson(BleOtherUtil.allSleepInfo)}")
            }

            2 -> {//睡眠数据
                if (step <= 0) return
                val userSleepInfo = UserSleepInfo()
                userSleepInfo.sleepType = 0
                userSleepInfo.createdTime = timestamp * 1000

                //睡眠质量类型以数据范围匹配
                userSleepInfo.sleepQuality = when {
                    step <= 0 -> SleepModeType.WAKE.value
                    step <= 19 -> SleepModeType.REM.value
                    step <= 79 -> SleepModeType.LIGHT.value
                    else -> SleepModeType.DEEP.value
                }
                BleOtherUtil.allSleepInfo.add(userSleepInfo)
                AizoSDKUtil.sleepTempAdd2DB(userSleepInfo)
                LogUtils.e(TAG, "HDU:onGetDataByDay sleep ${BleOtherUtil.allSleepInfo.size}")
//                LogUtils.e(TAG, "HDU:onGetDataByDay sleep ${JsonUtils.toJson(BleOtherUtil.allSleepInfo)}")
                JsonUtils.toJson(BleOtherUtil.allSleepInfo)
            }

            3 -> {
                if (heartrate <= 0) return
                val userHeartRate = UserHeartRate()
                userHeartRate.createdTime = timestamp * 1000
                userHeartRate.heartRate = heartrate
                BleOtherUtil.allHeartRates.add(userHeartRate)
                AizoSDKUtil.heartRateRepoAdd2DB(userHeartRate)
                LogUtils.e(TAG, "HDU:onGetDataByDay heartrate ${BleOtherUtil.allHeartRates.size}")
//                LogUtils.e(TAG, "HDU:onGetDataByDay heartrate ${JsonUtils.toJson(BleOtherUtil.allHeartRates)}")
                JsonUtils.toJson(BleOtherUtil.allHeartRates)
            }
        }
    }

    /**
     * 取得某天详细运动信息回调数据结束标记
     */
    override fun onGetDataByDayEnd(type: Int, timestamp: Long) {
        if (timestamp <= 0) return
        when (type) {
            1 -> {
            }

            2 -> {
            }

            3 -> {
                AizoSDKUtil.mCusSynthesisHealthExpandListenerList.forEach {
//                            it.onLatestHr(bean?.heartrate ?: 0, bean.toString(), bean?.time ?: 0)
                }
            }
        }
    }

    override fun onGetDeviceAction(p0: Int) {
    }

    override fun onGetBandFunction(p0: Int, p1: BooleanArray?) {
    }

    override fun onSetLanguage(p0: Int) {
    }

    override fun onSendWeather(p0: Int) {
    }

    override fun onSetAntiLost(p0: Int) {
    }

    /**
     * 打开关闭血压，血氧，疲劳度回调接口
     */
    override fun onSetBloodPressureMode(result: Int) {
    }

    /**
     * 当手环采集到有效心率血压血氧值后，会通过此命令返回数据给app
     * heartrate：心率;Systolicpressure:血压，收缩压;Diastolicpressure：血压，舒张压;Oxygen：血氧;Fatiguevalue：疲劳值
     */
    override fun onReceiveSensorData(
        heartrate: Int,
        systolicPressure: Int,
        diastolicPressure: Int,
        oxygen: Int,
        fatigueValue: Int
    ) {
        if (oxygen <= 0) return
        Log.e(TAG, "HDu-sdk onMeasureResult-onReceiveSensorData===oxygen:$oxygen")
//        HDuSendCommandManage.callRemoteOpenBlood(AizoSDKUtil.mHDuService, false)
        val mBloodOxygen = UserBloodOxygen()
        mBloodOxygen.createdTime = TimeUtils.getTimeDateLong()
        mBloodOxygen.bloodOxygen = oxygen
        AizoSDKUtil.bloodOxygenAdd2DB(mBloodOxygen)
        AizoSDKUtil.mCusSynthesisHealthExpandListenerList.forEach {
            doOnUiThread {
                it.onMeasureResult(
                    true,
                    CommonCusHealthType.BLOODOXYGEN.value,
                    mBloodOxygen.createdTime,
                    0,
                    mBloodOxygen.bloodOxygen,
                    0f,
                    0f
                )
            }
        }
    }

    override fun onSetBloodOxygenMode(p0: Int) {
    }

    override fun onReceiveSensorOxygenData(p0: Int) {
    }

    override fun onGetMultipleSportData(p0: Int, p1: String?, p2: Int, p3: Int) {
    }

    override fun onSetGoalStep(p0: Int) {
    }

    override fun onSetDeviceHeartRateArea(p0: Int) {
    }

    /**
     * 启动\关闭实时心率测量结束测试回调
     */
    override fun onSensorStateChange(
        type: Int,
        state: Int
    ) {//type 1:心率  2：血压血氧  , state 1:打开  0：关闭
        // 心率测量结束
//                if(state != 0) return
//                when (type){
//                    1->
//                    2->
//                }
    }

    override fun onReadCurrentSportData(p0: Int, p1: String?, p2: Int, p3: Int) {
    }

    override fun onGetOtaInfo(p0: Boolean, p1: String?, p2: String?) {
    }

    override fun onGetOtaUpdate(p0: Int, p1: Int) {
    }

    override fun onSetDeviceCode(p0: Int) {
    }

    override fun onGetDeviceCode(p0: ByteArray?) {
    }

    override fun onCharacteristicChanged(p0: String?, p1: ByteArray?) {
    }

    override fun onCharacteristicWrite(p0: String?, p1: ByteArray?, p2: Int) {
    }

    override fun onSetEcgMode(p0: Int, p1: Int) {
    }

    override fun onGetEcgValue(p0: Int, p1: IntArray?) {
    }

    override fun onGetEcgHistory(p0: Long, p1: Int) {
    }

    override fun onGetEcgStartEnd(p0: Int, p1: Int, p2: Long) {
    }

    override fun onGetEcgHistoryData(p0: Int, p1: IntArray?) {
    }

    override fun onSetDeviceName(p0: Int) {
    }

    override fun onGetDeviceRssi(p0: Int) {
    }

    override fun onSetReminder(p0: Int) {
    }

    override fun onSetReminderText(p0: Int) {
    }

    override fun onSetBPAdjust(p0: Int) {
    }

    override fun onSetTemperatureMode(p0: Int) {
    }

    override fun onGetTemperatureData(p0: Int, p1: Int) {
    }

    override fun onTemperatureModeChange(p0: Int) {
    }

    override fun onGetDeviceDial(
        p0: String?,
        p1: String?,
        p2: Int,
        p3: Int,
        p4: Int,
        p5: Int,
        p6: Int,
        p7: Int,
        p8: Int,
        p9: Int,
        p10: Int
    ) {
    }

    override fun onSetDeviceDialState() {
    }

    override fun onSetDeviceWallpaperState() {
    }

    override fun onEditDeviceDialCustom() {
    }

    override fun onGetDeviceDialCustom(p0: Int, p1: Int, p2: Int, p3: Int) {
    }

    override fun onSetFemaleReminder() {
    }

    override fun onNotifyClassicBtName(p0: String?) {
    }

    @SuppressLint("MissingPermission")
    override fun onNotifyClassicBtInfo(btState: Int, pareState: Int, deviceMac: String?, phoneMac: String?) {
        Log.i(TAG, "onNotifyClassicBtInfo [$btState, $pareState, $deviceMac, $phoneMac]")
        mClassicBtDeviceBtName = ""
        if (btState == 1) {
            var bBonded = false
            //得到所有已配对的蓝牙适配器对象
            val adapter = BluetoothAdapter.getDefaultAdapter()
            val devices = adapter.bondedDevices
            if (devices.size > 0) {
                val iterator: Iterator<*> = devices.iterator()
                while (iterator.hasNext()) {
                    val bluetoothDevice = iterator.next() as BluetoothDevice
                    //得到远程已配对蓝牙设备的mac地址
                    Log.i(TAG, "onNotifyClassicBtInfo : " + bluetoothDevice.address + " type: " + bluetoothDevice.type)
                    if (bluetoothDevice.address.equals(deviceMac, ignoreCase = true)) {
                        bBonded = true
                        Log.i(TAG, "device bonded already")
                    }
                }
            }

            if (pareState != 1) {
                val regex = "(.{2})"
                var macAddress = deviceMac!!.replace(regex.toRegex(), "$1:")
                macAddress = macAddress.substring(0, deviceMac.length - 1)
                Log.i(TAG, "device mac: $macAddress")
                val bd = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceMac)

                val intent = Intent(HDCommonAttributes.ACTION_NOTIFY_CLASSIC_BT_CREATE_BOND)
                intent.setPackage(getPackageName())
                intent.putExtra("device", bd)
                AppUtils.getContext().sendBroadcast(intent) ?: kotlin.run {
                    Log.i(TAG, "context null cannot send broadcast")
                }
            }
        }
    }

    override fun onNotifyContactCrc(p0: String?) {
    }

    override fun onNotifyAppId(p0: String?) {
    }

    override fun onGetPhoneVolume() {
    }


    override fun onNotifyBindedInfo(action: Int, state: Int) {
        when (action) {
            HDCommonAttributes.BOND_ACTION_INIT -> {
                if (state == HDCommonAttributes.BOND_STATE_NO) {
                    try {
                        AizoSDKUtil.mHDuService?.setBindedInfo(
                            HDCommonAttributes.BOND_ACTION_APP_START,
                            HDCommonAttributes.BOND_STATE_NO,
                            HDCommonAttributes.OS_TYPE
                        )
                    } catch (e: RemoteException) {
                        e.printStackTrace()
                    }
                } else if (state == HDCommonAttributes.BOND_STATE_YES) {
                }
            }

            HDCommonAttributes.BOND_ACTION_ACK -> {
                try {
                    AizoSDKUtil.mHDuService?.setBindedInfo(
                        HDCommonAttributes.BOND_ACTION_SUCCESS,
                        HDCommonAttributes.BOND_STATE_NO,
                        HDCommonAttributes.OS_TYPE
                    )
                } catch (e: RemoteException) {
                    e.printStackTrace()
                }
            }

            HDCommonAttributes.BOND_ACTION_ACK_CANCEL -> {
                Log.i(TAG, "onNotifyBindedInfo : disconnect device")

                // update sync state
                getContext().apply {
                    val intent = Intent(HDCommonAttributes.ACTION_NOTIFY_UNBOND_ACK)
                    intent.setPackage(this.packageName)
                    this.sendBroadcast(intent)
                }
            }

            HDCommonAttributes.BOND_ACTION_SUCCESS -> {
                Log.i(TAG, "onNotifyBindedInfo : bonded confirm")
            }

            HDCommonAttributes.BOND_ACTION_UNBOND_ACK -> {
                Log.i(TAG, "onNotifyBindedInfo : unbond device ack")

                // update sync state
                getContext().apply {
                    val intent = Intent(HDCommonAttributes.ACTION_NOTIFY_UNBOND_ACK)
                    intent.setPackage(this.packageName)
                    this.sendBroadcast(intent)
                }
            }

            else -> {}
        }
    }

    override fun onGetDeviceState(p0: Boolean, p1: Boolean, p2: Boolean) {
    }

    override fun onNotifyECardNeedUpdate(p0: ByteArray?) {
    }

    override fun onNotifySmsRspNeedUpdate(p0: ByteArray?) {
    }

    override fun onNotifySmsRspSend(p0: Int, p1: String?) {
    }

    override fun onGetChatgptAction(p0: Int) {
    }

    override fun onGetFactoryTestData(p0: ByteArray?) {
    }

    override fun onNotifyDialJsonContent(p0: String?) {
    }

    override fun onGetSportSteps(p0: Int) {
    }

    override fun onDeviceTestCmd() {
    }

    override fun onGetEqInfo2(p0: Int, p1: Int, p2: Int, p3: IntArray?): Int {
        return 0
    }

    override fun onSetEqInfo2(p0: Int, p1: Int, p2: Int, p3: IntArray?): Int {
        return 0
    }
}

